package com.ruoyi.kq.utils;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class StringParseUtil {
    // 日期和时间格式化器
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");
    private static final DateTimeFormatter TIME_FORMATTER_WITH_SECONDS = DateTimeFormatter.ofPattern("HH:mm:ss");


    /**
     * 查找集合中最早的时间
     *
     * @param setings 集合
     * @return 最早的时间，如果没有匹配项则返回 "暂未打卡"
     */
    public static String findEarliestTime(Set<String> setings) {
        String earliestTime = null;
        for (String time : setings) {
            if (isValidTime(time)) {
                if (earliestTime == null || compareTime(time, earliestTime) < 0) {
                    earliestTime = time;
                }
            }
        }
        return earliestTime != null ? earliestTime : "暂未打卡";
    }

    /**
     * 查找集合中 18:00 之后且距离 18:00 最近的时间
     *
     * @param setings 集合
     * @return 距离 18:00 最近的时间，如果没有匹配项则返回 "暂未打卡"
     */
    public static String findNearestAfterTen(Set<String> setings) {
        String nearestTime = null;
        for (String time : setings) {
            if (isValidTime(time) && compareTime(time, "18:00") >= 0 && time.trim().length() < 6) {
                if (nearestTime == null || compareTime(time, nearestTime) < 0) {
                    nearestTime = time;
                }
            }
        }
        return nearestTime != null ? nearestTime : "暂未打卡";
    }

    /**
     * 判断字符串是否为有效的时间格式（HH:mm）
     *
     * @param time 时间字符串
     * @return 是否为有效时间
     */
    private static boolean isValidTime(String time) {
        return time.matches("^([01]?\\d|2[0-3]):[0-5]\\d$");
    }

    /**
     * 比较两个时间字符串的大小
     *
     * @param time1 时间字符串 1
     * @param time2 时间字符串 2
     * @return 如果 time1 早于 time2，返回负数；如果相等，返回 0；否则返回正数
     */
    private static int compareTime(String time1, String time2) {
        String[] parts1 = time1.split(":");
        String[] parts2 = time2.split(":");
        int hour1 = Integer.parseInt(parts1[0]);
        int minute1 = Integer.parseInt(parts1[1]);
        int hour2 = Integer.parseInt(parts2[0]);
        int minute2 = Integer.parseInt(parts2[1]);

        if (hour1 != hour2) {
            return hour1 - hour2;
        } else {
            return minute1 - minute2;
        }
    }

    /**
     * 按原始字符串顺序解析并提取内容
     *
     * @param input 输入字符串
     * @return 按原始顺序提取的内容集合
     */
    public static Set<String> parseInOriginalOrder(String input) {
        if (input == null || input.trim().isEmpty()) {
            return Collections.emptySet();
        }

        Set<String> result = new LinkedHashSet<>();

        try {
            // 清理特殊字符，但保留分隔符
            String cleanedInput = input.replaceAll("[@\"']", "").trim();

            // 分割字符串，使用逗号和空格作为分隔符
            String[] segments = cleanedInput.split("[,\\s]+");

            for (String segment : segments) {
                segment = segment.trim();
                if (segment.isEmpty()) continue;

                // 处理可能包含日期或时间的段落
                List<String> extractedParts = extractPartsFromSegment(segment);
                result.addAll(extractedParts);
            }

        } catch (Exception e) {
            log.error("解析字符串时发生错误: {}", e.getMessage());
        }

        return result;
    }

    /**
     * 从段落中提取内容
     */
    private static List<String> extractPartsFromSegment(String segment) {
        List<String> parts = new ArrayList<>();

        // 日期模式
        Pattern datePattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
        // 时间模式（包括HH:mm:ss和HH:mm）
        Pattern timePatternWithSeconds = Pattern.compile("\\d{2}:\\d{2}:\\d{2}");
        Pattern timePatternWithoutSeconds = Pattern.compile("\\d{2}:\\d{2}(?!:\\d{2})");
        // 中文模式
        Pattern chinesePattern = Pattern.compile("[\\u4e00-\\u9fa5]+");

        // 临时存储所有匹配结果及其位置
        List<MatchResult> allMatches = new ArrayList<>();

        // 查找日期
        Matcher dateMatcher = datePattern.matcher(segment);
        while (dateMatcher.find()) {
            String date = dateMatcher.group();
            try {
                LocalDate.parse(date, DATE_FORMATTER);
                allMatches.add(new MatchResult(date, dateMatcher.start()));
            } catch (DateTimeParseException e) {
                log.warn("无效的日期格式: {}", date);
            }
        }

        // 查找带秒的时间
        Matcher timeMatcherWithSeconds = timePatternWithSeconds.matcher(segment);
        while (timeMatcherWithSeconds.find()) {
            String time = timeMatcherWithSeconds.group();
            try {
                LocalTime.parse(time, TIME_FORMATTER_WITH_SECONDS);
                allMatches.add(new MatchResult(time, timeMatcherWithSeconds.start()));
            } catch (DateTimeParseException e) {
                log.warn("无效的时间格式(带秒): {}", time);
            }
        }

        // 查找不带秒的时间
        Matcher timeMatcherWithoutSeconds = timePatternWithoutSeconds.matcher(segment);
        while (timeMatcherWithoutSeconds.find()) {
            String time = timeMatcherWithoutSeconds.group();
            // 确保不是已经匹配到的带秒时间的一部分
            if (!isPartOfTimeWithSeconds(time, segment, timeMatcherWithoutSeconds.start())) {
                try {
                    LocalTime.parse(time, TIME_FORMATTER);
                    allMatches.add(new MatchResult(time, timeMatcherWithoutSeconds.start()));
                } catch (DateTimeParseException e) {
                    log.warn("无效的时间格式: {}", time);
                }
            }
        }

        // 查找中文
        Matcher chineseMatcher = chinesePattern.matcher(segment);
        while (chineseMatcher.find()) {
            String chinese = chineseMatcher.group().trim();
            if (!chinese.isEmpty()) {
                allMatches.add(new MatchResult(chinese, chineseMatcher.start()));
            }
        }

        // 按位置排序
        allMatches.sort(Comparator.comparingInt(MatchResult::getPosition));

        // 提取排序后的内容
        for (MatchResult match : allMatches) {
            parts.add(match.getContent());
        }

        return parts;
    }

    /**
     * 检查时间是否是带秒时间的一部分
     */
    private static boolean isPartOfTimeWithSeconds(String time, String segment, int position) {
        // 检查这个位置后面是否紧跟着":数字数字"
        if (position + time.length() + 3 <= segment.length()) {
            String nextChars = segment.substring(position + time.length(), position + time.length() + 3);
            return nextChars.matches(":\\d{2}");
        }
        return false;
    }

    /**
     * 用于存储匹配结果及其位置的内部类
     */
    private static class MatchResult {
        private final String content;
        private final int position;

        public MatchResult(String content, int position) {
            this.content = content;
            this.position = position;
        }

        public String getContent() {
            return content;
        }

        public int getPosition() {
            return position;
        }
    }
}